package com.suyl.annotationdemo.core.aspect;

import com.suyl.annotationdemo.core.annotation.HandlingTime;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author : suyl
 * @version : v1.0.0
 * @date : 2020/3/25 16:04
 * @descr : 根据@HandlingTime注解获取需要打印执行时间的方法
 */
@Aspect
@Component
@Log4j2
public class HandlingTimeAspect {
    @Pointcut("@annotation(com.suyl.annotationdemo.core.annotation.HandlingTime)")
    public void handlingTimePointcut() {
    }

    @Around("handlingTimePointcut()&&@annotation(handlingTime)")
    public Object handlingTimeAround(ProceedingJoinPoint joinPoint, HandlingTime handlingTime) {
        long startTime = System.currentTimeMillis();
        try {
            Object proceed = joinPoint.proceed();
            String classType = joinPoint.getTarget().getClass().getName();
            Class<?> clazz = Class.forName(classType);
            String className = clazz.getName();
            String classSimpleName = clazz.getSimpleName();
            String methodName = joinPoint.getSignature().getName();
            log.info("调用{}（简名{}）类的{}({})方法执行时间：{}ms", className, classSimpleName, methodName, handlingTime.value(), (System.currentTimeMillis() - startTime));
            return proceed;
        } catch (Throwable throwable) {
            log.error("调用方法发生异常，执行时间：{}ms", (System.currentTimeMillis() - startTime));
            throwable.printStackTrace();
        }
        return null;
    }
}
